import cn.hutool.db.Db;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import constant.Constant;
import domain.Column;
import domain.Table;
import handler.SheetLinkCellWriteHandler;
import handler.TableSheetAfterHandler;

import java.util.List;

public class Main {

    public static void main(String[] args) {

        ExcelWriter excelWriter = EasyExcel.write(Constant.OUT_PATH).build();

        try {
            List<Table> tables = Db.use().query(Constant.QUERY_TABLES_SQL, Table.class);

            // 第一个目录sheet
            WriteSheet sheet = EasyExcel.writerSheet(Constant.INDEX)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .registerWriteHandler(new SheetLinkCellWriteHandler())
                    .build();
            sheet.setClazz(Table.class);
            excelWriter.write(tables, sheet);

            // 其他表sheet
            for (Table table : tables) {
                List<Column> list = Db.use().query(Constant.QUERY_COLUMNS_SQL, Column.class, table.getTableName());
                WriteSheet sheet1 = EasyExcel.writerSheet(table.getComments())
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .registerWriteHandler(new TableSheetAfterHandler(table.getComments(), table.getTableName()))
                        .relativeHeadRowIndex(1)
                        .build();
                sheet1.setClazz(Column.class);
                excelWriter.write(list, sheet1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            excelWriter.finish();
        }

    }
}
